'use strict';

const express = require('express');
const dbutility = require('../../common/dbutility');
const gputility = require('../../common/gputility');
const cabutility = require('../../common/cabutility');
const utility = require('../../common/utility');
const logger = require('../../common/logutility').logger('dlvExpTest');
const rdsutility = require('../../common/rdsutility');
let router = express.Router();

router.get('/', function(req, res) {
    gputility.excuteGP(getGP(req, res));
});

router.post('/', function(req, res) {
    gputility.excuteGP(postGP(req, res));
});

function* getGP(req, res) {
    try {
        let expCabinetNo = req.session.expDlv.expCabinetNo;
        res.render('./cou/dlvExpTest', { cabNo: expCabinetNo });
    } catch (e) {
        logger.error(e);
        res.redirect('/error');
    }
}

function* postGP(req, res) {
    try {
        let cabNo = req.session.expDlv.expCabinetNo;
        let expNo = req.session.expDlv.expNo;
        let expCouTel = req.session.userTel;
        let expCabinetNo = cabNo;

        //生成取件码
        let cabPwd = utility.createCabPwd(cabNo);
        while (yield rdsutility.hasCabPwdInUse(cabPwd)) {
            //如果取件码已使用，那么重新生成
            cabPwd = utility.createCabPwd(cabNo);
        }

        //检测快递柜是否已关闭
        let cab = yield dbutility.cabModel.getCabByCabNo(cabNo);
        let cabPortName = cab.cabPortName;
        let cabCheckCmd = cab.cabCheckCmd;
        let cabOpenStatus = cab.cabOpenStatus;
        let cmdRepeat = 0;
        let cabLockStatus;
        while (cmdRepeat < 3 && cabLockStatus === cabOpenStatus) {
            cabLockStatus = yield cabutility.checkCab(cabPortName, cabCheckCmd)
            cmdRepeat += 1;
        }

        if (cabLockStatus === cabOpenStatus) {
            res.render('./cou/dlvExpTest', { cabNo, errorInfo: '确认投递成功，请先关闭快递柜！' });
        } else {
            yield dbutility.cabModel.updateCabToInUse(cabNo, cabPwd);
            yield dbutility.expModel.updateExpToDlved(expNo, expCouTel, expCabinetNo)
            yield dbutility.msgModel.insertMsg(expNo);
            yield rdsutility.add(addCabPwdInUse);

            logger.info('Dlv Exp Info:');
            logger.info(req.session.expDlv);

            res.redirect('/dlvExpCmp');
        }
    } catch (e) {
        logger.error(e);
        res.redirect('/error');
    }
}

module.exports = router;